package com.yaowk.sfp.utils.generator;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Data
public class ModelGenerator extends AbstractGenerator {

    private String classTemplate = "@Getter%n@Setter%n@ToString%npublic class %s extends %s {%n%n";
    private ModelBaseGenerator modelBaseGenerator;

    @Override
    public void generator() {
        List<Class> entities = getEntities();
        String packageName = getPackageName();
        if (StringUtils.isEmpty(packageName)) {
            return;
        }
        String path = GeneratorUtils.getPath(packageName, getBasePath());
        for (Class clazz : entities) {
            // 构建类名
            String className = buildClassName(clazz);
            String newClazz = buildClassType(clazz);
            File file = new File(path + "/" + className + ".java");
            if (file.exists()) {
                System.out.println(newClazz + "已存在");
                continue;
            }
            StringBuilder stringBuilder = new StringBuilder();

            // 设置包名
            appendPackage(stringBuilder);

            // 组织引用类
            Set<String> imports = new HashSet<>();
            imports.add(Getter.class.getTypeName());
            imports.add(Setter.class.getTypeName());
            imports.add(ToString.class.getTypeName());
            imports.add(modelBaseGenerator.buildClassType(clazz));

            appendImport(stringBuilder, imports);
            // 设置类
            stringBuilder.append(String.format(classTemplate, className, modelBaseGenerator.buildClassName(clazz)));
            stringBuilder.append("\n}");

            // 执行生成
            GeneratorUtils.write(file, stringBuilder);
            System.out.println(newClazz);
        }
    }
}
